import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wch/constant/event_bus_global.dart';
import 'package:wch/helper/user_wrap_helper.dart';
import 'package:wch/model/ble.dart';
import 'package:wch/model/flag_model.dart';
import 'package:wch/page/set_wifi.dart';
import 'package:wch/utils/color_utils.dart';
import 'package:wch/utils/loading_utils.dart';
import 'package:wch/utils/navigator_utils.dart';
import 'package:wch/widget/common_widget.dart';

import 'dart:convert' as convert;

import '../constant/resource_constant.dart';
import '../helper/flags_widget.dart';
import '../helper/mqtt.dart';
import '../helper/preferences_helper.dart';
import '../model/patient_label.dart';
import '../model/patient_label_list.dart';
import '../native/net_business.dart';
import '../utils/log_utils.dart';
import '../utils/text_utils.dart';
import '../utils/toast_utils.dart';
import '../widget/alert_view.dart';
import '../widget/padding_widget.dart';
import '../widget/text_widget.dart';

class MatchDevicePage extends StatefulWidget {
  MatchDevicePage({super.key, required this.model, required this.bleModel, required this.labelList});

  final UserWrapModel model;

  final BleModel bleModel;

  List<PatientLabelListShopLabelList>? labelList;

  @override
  State<MatchDevicePage> createState() => _MatchDevicePageState();
}

class _MatchDevicePageState extends State<MatchDevicePage> {

  OverlayEntry? entry;
  List<Widget>? flagWidgets;
  double flagHeight = 0;

  @override
  void initState() {
    super.initState();
    createFlagsWidget();
  }

  void createFlagsWidget() {
    Text label = Text(
      '采集标签：',
      style: TextStyle(fontSize: 12, color: Colors.white),
    );

    double maxWidth = ScreenUtil().screenWidth - 170.w;
    double labelWidth = TextUtils.getTextSize('采集标签：', maxWidth, 12).width + 10;

    List<FlagModel> flags = [];
    flagHeight = 0;

    if (widget.labelList != null) {
      for(int i = 0; i < widget.labelList!.length; i ++) {
        PatientLabelListShopLabelList list = widget.labelList![i]!;
        Color textColor = ColorUtils.getColorFromHex(list.colour!);
        flags.add(FlagModel(list.name!, false, Colors.white, textColor));
      }
    }

    flagWidgets = FlagsWidget.getFlagsWidgetAndHead2(
        label, labelWidth, flags, maxWidth, 180, 10, (_flagHeight) {
      flagHeight = _flagHeight;
    });
  }


  @override
  void dispose() {
    super.dispose();
    ///需要清除用户名，用户名是前面用来判断设备是否已分配出去的标识
    widget.bleModel.userModel!.name = null;
  }

  @override
  Widget build(BuildContext context) {


    return CommonScaffold(
        title: '配对设备',
        body: Container(
            margin: EdgeInsets.all(15.w),
            color: Color(0xFFF8F9FB),
            child: Column(children: [
              Container(
                height: 70.h + flagHeight + (widget.model.name!.length > 3 ? 20.h : 0),
                width: ScreenUtil().screenWidth - 30.w,
                decoration: BoxDecoration(
                    color: themeColor,
                    borderRadius: BorderRadius.all(Radius.circular(7.5.w))),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    VerPadding(20.h),
                    widget.model.name!.length <= 3 ? Row(
                      children: [
                        HorPadding(17.5.w),
                        Image.asset(
                          widget.model.sex == '男' ? patientMaleImg : patientFemaleImg,
                          width: 35.w,
                          height: 35.w,
                        ),
                        HorPadding(5.w),
                        Container(
                            constraints: BoxConstraints(
                                maxWidth: ScreenUtil().screenWidth - 280.w),
                            child: MyText(widget.model.name!,
                                overflow: TextOverflow.ellipsis,
                                color: Colors.white,
                                fontSize: 20)),
                        HorPadding(5.w),
                        Container(
                          width: 20.w,
                          height: 20.w,
                          decoration: BoxDecoration(
                            image: DecorationImage(
                                image: AssetImage(widget.model.sex == '男' ? patientMale2Icon : patientFemale2Icon,),
                                fit: BoxFit.none,
                                scale: 2),
                            color: Color(0xFFDEE5FB),
                            borderRadius:
                                BorderRadius.all(Radius.circular(10.w)),
                          ),
                        ),
                        HorPadding(25.w),
                        F14TitleText('${widget.model.age}岁', color: Colors.white),
                        HorPadding(4.w),
                        Expanded(
                            child: F14TitleText(widget.model.mobile!,
                                color: Colors.white)),
                        HorPadding(17.5.w),
                      ],
                    ) : Column(
                      children: [
                        Row(
                          children: [
                            HorPadding(17.5.w),
                            Image.asset(
                              widget.model.sex == '男' ? patientMaleImg : patientFemaleImg,
                              width: 35.w,
                              height: 35.w,
                            ),
                            HorPadding(5.w),
                            Container(
                                constraints: BoxConstraints(
                                    maxWidth: ScreenUtil().screenWidth - 138.w),
                                child: MyText(widget.model.name!,
                                    overflow: TextOverflow.ellipsis,
                                    color: Colors.white,
                                    fontSize: 20)),
                            HorPadding(5.w),
                            Container(
                              width: 20.w,
                              height: 20.w,
                              decoration: BoxDecoration(
                                image: DecorationImage(
                                    image: AssetImage(widget.model.sex == '男' ? patientMale2Icon : patientFemale2Icon,),
                                    fit: BoxFit.none,
                                    scale: 2),
                                color: Color(0xFFDEE5FB),
                                borderRadius:
                                BorderRadius.all(Radius.circular(10.w)),
                              ),
                            ),
                            HorPadding(25.w),
                          ],
                        ),
                        VerPadding(5.h),
                        Row(
                          children: [
                            HorPadding(17.5.w),
                            F14TitleText('${widget.model.age}岁', color: Colors.white),
                            HorPadding(4.w),
                            Expanded(
                                child: F14TitleText(widget.model.mobile!,
                                    color: Colors.white)),
                            HorPadding(17.5.w),
                          ],
                        )
                      ],
                    ),
                    Row(
                      children: [
                        Container(
                          margin: EdgeInsets.symmetric(horizontal: 15.w),
                          width: ScreenUtil().screenWidth - 170.w,
                          height: flagHeight,
                          child: Stack(
                            children: flagWidgets!,
                          ),
                        ),
                        GestureDetector(
                          onTap: (){
                            editLabels();
                          },
                          child: Container(
                            width: 84.w,
                            height: 31.h,
                            // padding: EdgeInsets.symmetric(horizontal: 6.w),
                            decoration: BoxDecoration(
                                borderRadius:
                                    BorderRadius.all(Radius.circular(15.5.h)),
                                border:
                                    Border.all(color: Colors.white, width: 0.5)),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              children: [
                                Image.asset(
                                  addFlagIcon,
                                  width: 17.w,
                                  height: 17.w,
                                ),
                                F12TitleText('添加标签', color: Colors.white)
                              ],
                            ),
                          ),
                        ),
                        // HorPadding(10.w),
                      ],
                    ),
                  ],
                ),
              ),
              VerPadding(10.h),
              Container(
                height: 102.h,
                width: ScreenUtil().screenWidth - 30.w,
                padding: EdgeInsets.symmetric(horizontal: 20.w),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(7.5.w))),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    VerPadding(20.h),
                    F15TitleText('配对设备', color: Color(0xFF262626)),
                    VerPadding(15.h),
                    F15TitleText(
                      widget.bleModel.deviceName,
                      color: F2TextColor,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ],
                ),
              ),
              Expanded(child: Container()),
              Container(
                  margin: EdgeInsets.symmetric(horizontal: 40.w),
                  child: CommonBtn(title: '确认配对', callback: (){
                    // NetBusiness().deliveryDevice(widget.bleModel!.deviceId!, widget.model.userId!).then((value){
                    //   if (value) {
                    //     // ToastUtils.showToast(msg: '分配设备成功');
                    //
                    //     NavigatorUtil.pop(context);
                    //     String publicTopic = 'RL/SAAS/${widget.bleModel!.deviceName}/APP';
                    //     Map<String, dynamic> msg = {};
                    //     msg['messageType'] = 'bindSickPerson';
                    //     msg['data'] = {
                    //       'token':PreferencesHelper.getUserToken(),
                    //       'sickPersonId':widget.model.userId
                    //     };
                    //     mqttPublicMsg(publicTopic, convert.jsonEncode(msg));

                        ///跳转到设置 wifi 界面

                        NavigatorUtil.replace(context, StartSetWifiPage(bleModel: widget.bleModel, model: widget.model,));

                      // } else {
                      //   ToastUtils.showToast(msg: '分配设备失败，请稍后再试');
                      // }
                    // });
                  },)),
              VerPadding(60.h)
            ])));
  }

  Future<List<PatientAllLabelData>?> requestAllLabels() async{
    PatientLabelModel labelData = await NetBusiness().patientAllLabel(0);
    return labelData.data;
  }
  void editLabels () async{

    Loading.getIns().loading(msg: '正在加载患者标签');
    List<PatientAllLabelData>? labelData = await requestAllLabels();
    Loading.getIns().hide();
    if (labelData != null && labelData.isNotEmpty) {
      for (int i = 0; i < labelData!.length; i ++) {
        labelData[i].isChecked = false;
      }
      List<
          PatientLabelListShopLabelList>? patientShopLabelList = widget
          .labelList;
      if (patientShopLabelList != null &&
          patientShopLabelList.isNotEmpty) {
        for (int i = 0; i <
            labelData!.length; i ++) {
          for (int j = 0; j <
              patientShopLabelList!.length; j ++) {
            PatientLabelListShopLabelList label = patientShopLabelList[j];
            if (labelData[i].name == label.name) {
              labelData[i].isChecked = true;
            }
          }
        }
      }
    } else {
      Loading.getIns().loading(msg: '请求失败，请稍后再试');
      return;
    }
    entry = OverlayEntry(builder: (ctx){
      return EditFlagAlert(title: '添加采集标签', entry: entry!, flagModels: labelData!, actionCallback: (List<PatientAllLabelData> labelList){
        if (labelList.isEmpty){
          return;
        }
        List<Map<String, String>> list = [];
        for(int i = 0; i < labelList.length; i ++) {
          PatientAllLabelData data = labelList[i];
          if (data.isChecked) {
            Map<String, String> m = <String, String>{};
            m['id'] = data.id!;
            m['name'] = data.name!;
            m['colour'] = data.colour!;
            list.add(m);
          }
        }

        Loading.getIns().loading(msg: '正在编辑患者标签');
        NetBusiness().patientAddLabel(widget.model.userId!, list).then((value) {
          Loading.getIns().hide();
          if (value) {
            ///重新查询患者详情，以拿到更新后的患者标签
            widget.labelList?.clear();
            widget.labelList ??= [];
            LogUtils.log('list.len=${list.length}');
            for (int i = 0; i < list.length; i ++) {
              Map<String, String> m = list[i];
              PatientLabelListShopLabelList label = PatientLabelListShopLabelList();
              label.colour = m['colour'];
              label.id = m['id'];
              label.name = m['name'];
              widget.labelList!.add(label);
            }
            ToastUtils.showToast(msg: '标签编辑成功');
            setState(() {
              createFlagsWidget();
            });
            globalEventBus.fire(RefreshUserModel());
          }
        });
        });
    });
    Overlay.of(context).insert(entry!);

  }
}

class RefreshUserModel {

}
